//
//  forgetPasswordViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-10-1.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "forgetPasswordViewController.h"

@interface forgetPasswordViewController ()<UITextFieldDelegate>
{
    int second;
    NSTimer * _timer;
    UIButton *getVerifyCodeBtn;
}
@end

@implementation forgetPasswordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"忘记密码";
    self.leftBtn.hidden = NO;
    self.contentView.backgroundColor = UIColorFromRGB(0xffffefa);
    
    phoneNumber = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_IPHONE]];
    
    UIButton *finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    finishButton.frame =  CGRectMake(10, 5, 40, 30);
    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [finishButton addTarget:self action:@selector(finishButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIView *assoryView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 40)];
    assoryView.backgroundColor = [UIColor redColor];
    [assoryView addSubview:finishButton];
    
    registerField = [[UITextField alloc]initWithFrame:CGRectMake(20, 30,(UI_SCREEN_WIDTH - 20*2), 40)];
    registerField.placeholder = @"点击输入您的手机号";
    registerField.textAlignment = NSTextAlignmentLeft;
    registerField.tag = 333;
    registerField.clearButtonMode = UITextFieldViewModeWhileEditing;
    registerField.keyboardType = UIKeyboardTypeNumberPad;
    registerField.delegate = self;
    UIImageView *regLeftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    regLeftView.image = [UIImage imageNamed:@"userNumber"];
    regLeftView.backgroundColor = [UIColor clearColor];
    registerField.leftView = regLeftView;
    registerField.borderStyle = UITextBorderStyleRoundedRect;
    registerField.leftViewMode  = UITextFieldViewModeAlways;
    [self.contentView addSubview:registerField];
    
    pwdField = [[UITextField alloc]initWithFrame:CGRectMake(20, height_y(registerField)+10,(UI_SCREEN_WIDTH - 20*2), 40)];
    pwdField.placeholder = @"请输入新密码";
    pwdField.textAlignment = NSTextAlignmentLeft;
    pwdField.secureTextEntry = YES;
    pwdField.tag = 333;
    pwdField.delegate = self;
    pwdField.borderStyle = UITextBorderStyleRoundedRect;
    UIImageView *pwdLeftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    pwdLeftView.image = [UIImage imageNamed:@"password"];
    pwdField.leftView = pwdLeftView;
    pwdField.leftView.hidden = NO;
    pwdField.leftViewMode  = UITextFieldViewModeAlways;
    [self.contentView addSubview:pwdField];
    
    verifyCodeField = [[UITextField alloc]initWithFrame:CGRectMake(20,pwdField.frame.origin.y +  pwdField.frame.size.height+20, 160, 40)];
    verifyCodeField.placeholder = @"请输入手机验证码";
    verifyCodeField.textAlignment = NSTextAlignmentLeft;
    verifyCodeField.tag = 444;
    verifyCodeField.delegate = self;
    verifyCodeField.borderStyle = UITextBorderStyleRoundedRect;
    verifyCodeField.keyboardType = UIKeyboardTypeNumberPad;
    verifyCodeField.inputAccessoryView = assoryView;
    [self.contentView addSubview:verifyCodeField];
    
    getVerifyCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    getVerifyCodeBtn.layer.masksToBounds = YES;
    getVerifyCodeBtn.layer.cornerRadius = 6.0f;
    getVerifyCodeBtn.frame = CGRectMake(verifyCodeField.frame.size.width+verifyCodeField.frame.origin.x+10, pwdField.frame.origin.y+pwdField.frame.size.height+20, 103, 40) ;
    getVerifyCodeBtn.backgroundColor = UIColorFromRGB(0xff6800);;
    [getVerifyCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    getVerifyCodeBtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    [getVerifyCodeBtn setBackgroundImage:[UIImage imageNamed:@"pressedBg"] forState:UIControlStateHighlighted];
    [getVerifyCodeBtn addTarget:self action:@selector(getVerifyCodeBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:getVerifyCodeBtn];
    
    UIView *buttomView = [[UIView alloc]initWithFrame:CGRectMake(0, UI_SCREEN_HEIGHT-68-64, UI_SCREEN_WIDTH, 68)];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,0, UI_SCREEN_WIDTH, 1/2.0)];
    lineView.backgroundColor = UIColorFromRGB(0xd3d2d2);
    [buttomView addSubview:lineView];
    buttomView.backgroundColor = UIColorFromRGB(0xffffff);
    [self.contentView addSubview:buttomView];
    
    UIButton *comfirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    comfirmButton.frame = CGRectMake(15, 12, (UI_SCREEN_WIDTH - 2*15), 40);
    comfirmButton.backgroundColor =UIColorFromRGB(0xff6800);;
    comfirmButton.layer.masksToBounds = YES;
    comfirmButton.layer.cornerRadius = 6.0f;
    [comfirmButton setBackgroundImage:[UIImage imageNamed:@"pressedBg"] forState:UIControlStateHighlighted];
    [comfirmButton setTitle:@"提交" forState:UIControlStateNormal];
    [comfirmButton addTarget:self action:@selector(comfirmButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    comfirmButton.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    [buttomView addSubview:comfirmButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ====UITextFieldDEleget
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [pwdField resignFirstResponder];
    [verifyCodeField resignFirstResponder];
    return  YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (pwdField.text.length >= 10 && pwdField.text.length <=6) {
        [XDTools showTips:@"密码需6-10位" toView:self.contentView];
    }
}

-(void)getVerifyCodeBtnPressed
{
    
    if (![XDTools chickIphoneNumberRight:registerField.text]) {
        [XDTools showTips:@"请输入正确的手机号码" toView:self.view];
    }else{
        [self sendMessageToThePhone];
    }
}
-(void)sendMessageToThePhone
{
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    NSDictionary *requestDic = @{@"MobilePhone":registerField.text,@"Type":@"W"};
    ASIHTTPRequest *request = [XDTools postRequestWithDict:requestDic API:API_SMSGET];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        NSDictionary *resultDic = [XDTools JSonFromString:[mrequest responseString]];
        DDLOG(@"res....%@",resultDic);
        if ([[resultDic objectForKey:@"status"] intValue]==1) {
            verifyCode = [[resultDic objectForKey:@"data"]objectForKey:@"Code"];
            second = 60;
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeCodeBtn) userInfo:nil repeats:YES];
            getVerifyCodeBtn.userInteractionEnabled = NO;
        }else{
            [XDTools showTips:[requestDic objectForKey:@"msg"] toView:self.contentView];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];
}

- (void)changeCodeBtn{
    second--;
    [getVerifyCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%d)",second] forState:UIControlStateNormal];
    [getVerifyCodeBtn setBackgroundColor:RGBA(203, 203, 203, 1)];
    DDLOG(@"codeBtn.titleLabel.text = %@",getVerifyCodeBtn.titleLabel.text);
    if (!second) {
        [getVerifyCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        getVerifyCodeBtn.userInteractionEnabled = YES;
        [_timer setFireDate:[NSDate distantFuture]];
        _timer = nil;
        [getVerifyCodeBtn setBackgroundColor:RGBA(241, 141, 0, 1)];
    }
}

-(void)backPrePage
{
    [_timer setFireDate:[NSDate distantFuture]];
    _timer = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)comfirmButtonPressed
{

//     [verifyCodeField resignFirstResponder];

    if (pwdField.text.length <= 10 && pwdField.text.length >= 6) {
        
        if (![XDTools chickIphoneNumberRight:registerField.text]) {
            [XDTools showTips:@"请输入正确的手机号" toView:self.contentView];
            return;
        }else{
            [verifyCodeField resignFirstResponder];

            if (!(IS_NOT_EMPTY(verifyCodeField.text))){
                [XDTools showTips:@"请输入验证码" toView:self.view];
                return;
            }
            
            if(![XDTools NetworkReachable]){
                [XDTools showTips:brokenNetwork toView:self.view];
                return;
            }
            if (![[NSString stringWithFormat:@"%@",verifyCode] isEqualToString:[NSString stringWithFormat:@"%@",verifyCodeField.text]]) {
                [XDTools showTips:@"请输入正确的验证码" toView:self.contentView];
                return;
            }
            NSDictionary *requestDic = @{@"UserPass": [NSString stringWithFormat:@"%@",pwdField.text],@"UserName":[NSString stringWithFormat:@"%@",registerField.text],@"UserCode":[NSString stringWithFormat:@"%@",verifyCodeField.text]};
            
            ASIHTTPRequest *request = [XDTools postRequestWithDict:requestDic API:API_PWD_foget];
            __weak ASIHTTPRequest * mrequest = request;
            [request setTimeOutSeconds:12];
            [request setCompletionBlock:^{
                NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
                if ([[tmpDict objectForKey:@"status"] intValue] == 1) {
//                    [self initUserInfo:tmpDict];
                    [self finishButtonPressed];
                    [XDTools showTips:@"密码修改成功" toView:self.contentView];
                    
                    [self performSelector:@selector(delyaToPush) withObject:nil afterDelay:.8];
                }else{
                    if (IS_NOT_EMPTY([tmpDict objectForKey:@"msg"])) {
                        [XDTools showTips:[tmpDict objectForKey:@"msg"] toView:self.contentView];
                    }else{
                        [XDTools showTips:@"服务器异常" toView:self.contentView];
                    }
                    
                }
            }];
            [request setFailedBlock:^{
                if (mrequest.error.code == 2) {
                    [XDTools showTips:@"网络请求超时" toView:self.view];
                }
            }];
            [request startAsynchronous];
        }
        
    }else{
        [XDTools showTips:@"密码需6-10位" toView:self.contentView];
        return;
    }
}


-(void)initUserInfo:(NSDictionary *)userInfo
{
    
    if ([[userInfo objectForKey:@"data"] objectForKey:@"token"] && [[userInfo objectForKey:@"data"] objectForKey:@"ID"]) {
        [[NSUserDefaults standardUserDefaults]setObject:[[userInfo objectForKey:@"data"] objectForKey:@"ID"] forKey:kMY_USER_ID];
        [[NSUserDefaults standardUserDefaults]setObject:[[userInfo objectForKey:@"data"] objectForKey:@"token"] forKey:kMY_USER_TOKEN];
        [[NSUserDefaults standardUserDefaults]setObject:phoneNumber forKey:kMY_USER_IPHONE];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        [XDTools showTips:@"服务器参数错误" toView:self.contentView];
    }
    
}
-(void)finishButtonPressed
{
    [pwdField resignFirstResponder];
    [verifyCodeField resignFirstResponder];
}
-(void)delyaToPush
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
